"""
Specifies constants used in drawing the charts. 
"""
import os
import atlas
import pychartdir

# load and set the chartdirector license
CHARTDIRECTOR_LICENSE = os.getenv('CHARTDIRECTOR_LICENSE', '')
if CHARTDIRECTOR_LICENSE:
    #atlas.info('chartdir license found')
    pychartdir.setLicenseCode( CHARTDIRECTOR_LICENSE ) 
else:
    atlas.warn('chartdir license NOT found')

# setting constants
ARROW_POLYGON1 = [ -5, 0, 0, 0, 5, -0, 0, 5 ]

# setting constants
ARROW_POLYGON2 = [ -6, 0, 0, 0, 6, -0, 0, 6 ]

# colors
BLUE, RED, GREEN = 0x0000DD, 0xDD0000, 0x00DD00 
GREY, LIGHT, BLACK = 0xCECECE, 0xEFEFEF, 0x000000
WHITE, PURPLE, ORANGE = 0xFFFFFF, 0x990066, 0xFF3300
TEAL, CRIMSON, GOLD = 0x009999, 0xDC143C,  0xFFD700
NAVY, SIENNA = 0x000080, 0xA0522D 
LIGHT_GREEN, SPRING_GREEN, YELLOW_GREEN = 0x33FF00, 0x00FF7F, 0x9ACD32

# other constants
TRANSPARENT  = pychartdir.Transparent
TOPCENTER    = pychartdir.TopCenter
NOVALUE      = pychartdir.NoValue
CIRCLESYMBOL = pychartdir.CircleSymbol
CROSS        = pychartdir.CrossShape(0.1)
CENTER       = pychartdir.Center
PNG          = pychartdir.PNG

# plot types
LINE, BARS, SCATTER, VECTOR, SEGMENT, STRIPES = "LINE BARS SCATTER VECTOR SEGMENT STRIPES".split()

# nucleosome specific intervals relative to the start site of the nucleosome
STRIPE_COORDS = [(0, 4), (9, 14), (19, 25), (30, 35), (40, 45), (50, 56), (61, 66), (71, 76), (81, 86), (91, 97), (102, 107), (112, 117), (122, 128), (133, 138), (143, 147)]

def reorder( data):
    """
    Some operations need intervals to always be start<end
    """
    out = []
    for start, end, label in data:
        if start>end:
            start, end = end, start
        out.append( (start, end, label) )
    return out

def remove_overlapping( data, width, xscale, fontsize=12 ):
    """
    Removes labels that may overlap at a given fontsize
    Expects the data to be a list of triplets of the form (start, end, label)

    >>> data = [ (1, 2, 'One'), ( 2, 3, 'Two'),  (4,5, 'Three') ]
    
    #>>> remove_overlapping( data=data, width=100, xscale=[0 , 10])
    #[(1, 2, 'One'), (2, 3, ''), (4, 5, 'Three')]
    """
    scale = (xscale[1] - xscale[0]) / float(width)
    last  = -1
    out   = []
    for start, end, label in data:
        mid = (start + end)/2
        if mid > last:
            last = mid + len( label ) * scale * fontsize
        else:
            label = ''
        out.append ( (start, end, label) ) 
    return out            

def chart_options( **kwds ):
    """
    Represents parameters used to customize a chart. Provides a namespace for all options. 
    Uses the variable naming convention that M{ChartDirector} internally uses. See the M{ChartDirector}
    docs for reference.

    >>> opts = chart_options( xyz=123, h=50 )
    >>> opts.w, opts.h, opts.lw, opts.xyz
    (800, 50, 1, 123)
    """
    default_options = dict( 
        
        # widht, height
        w=800, h=200, 
        
        # padding: top, bottom, right, left
        tpad=20, bpad=20, rpad=60, lpad=60, 
        
        # labels and axis position
        show_labels=True, XAxisOnTop=0, ylabel='Y-Label', ylabel2='', 
        xscale=[1,100], yscale=[], yscale2=[],
        
        # colors
        hGridColor=-1, vGridColor=GREY, fontSize=13, lw=1,
        fgColor=BLACK, bgColor=WHITE, altBgColor=-1, edgeColor=GREY, 
        XAxisColor=BLACK, YTickColor=BLACK, barColor=BLACK,

        # arrow
        arrow_polygon = ARROW_POLYGON1, stripe_coords=STRIPE_COORDS
    )
    opt = atlas.Param( **kwds )
    opt.defaults( default_options )
    return opt

def track_options( **kwds ):
    """
    Returns the default track options
    """
    param = chart_options( 
        lw=12, XAxisColor=TRANSPARENT, YTickColor=TRANSPARENT, 
        tpad=0, bpad=0, h=60, yscale=[-10, 10],
    )
    param.update( kwds )
    return param

def test( verbose=0 ):
    "Performs module level testing"
    import doctest
    doctest.testmod( optionflags=doctest.ELLIPSIS + doctest.NORMALIZE_WHITESPACE, verbose=verbose )

if __name__ == "__main__":
    test()
